﻿using System;
using System.Collections.Generic;
using System.Text;
using Com.Toook.ParseHtml.Entity;
using Com.Toook.Common;
using MySql.Data.MySqlClient;
using System.Collections.Specialized;
using System.Collections;
using System.Data;

namespace Com.Toook.ParseHtml
{
    public class SaveResultToMySql
    {
        /// <summary>
        /// 保存分类页面中的Url等结果到SiteKindPageUrlTemp***表中(表名在xml在配置)。如果url已经存在返回true, 不存在返回FALSE
        /// </summary>
        /// <param name="result"></param>
        /// <returns>如果url已经存在返回true, 不存在返回FALSE</returns>
        public static bool SaveKindUrl(ResultKind result)
        {
            bool existSameUrl = true;
            

            string command = "insert into " + result.SaveToTableName + "(url, title, summary, img, siteKindId, kindUrl, author, actor, year, area ) "
                + " values(@url, @title, @summary, @img, @siteKindId, @kindUrl, @author, @actor, @year, @area) ";
            MySqlConnection con = MySqlHelperMy.GetConnection();
            MySqlCommand cmd = new MySqlCommand(command, con);
            cmd.Parameters.Add("@url", MySqlDbType.String, 200).Value = result.Url;
            cmd.Parameters.Add("@title", MySqlDbType.String, 40).Value = result.Title;
            cmd.Parameters.Add("@summary", MySqlDbType.String).Value = result.Summary;
            cmd.Parameters.Add("@img", MySqlDbType.String, 200).Value = result.Img;
            cmd.Parameters.Add("@siteKindId", MySqlDbType.String, 20).Value = result.SiteKindId;
            cmd.Parameters.Add("@kindUrl", MySqlDbType.String, 200).Value = result.KindPageUrl;
            cmd.Parameters.Add("@author", MySqlDbType.String, 20).Value = result.Author;
            cmd.Parameters.Add("@actor", MySqlDbType.String, 20).Value = result.Actor;
            cmd.Parameters.Add("@year", MySqlDbType.String, 4).Value = result.Year;
            cmd.Parameters.Add("@area", MySqlDbType.String, 20).Value = result.Area;

            MySqlCommand existCmd = new MySqlCommand("select count(*) number from " + result.SaveToTableName + " where url=@url", con);
            existCmd.Parameters.Add("@url", MySqlDbType.String, 200).Value = result.Url;
            try
            {
                con.Open();
                int number = int.Parse(existCmd.ExecuteScalar().ToString());
                if (number == 0)
                {
                    existSameUrl = false;//不存在相同url的记录
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error("SaveKindUrl保存结果错误", ex);
            }
            finally
            {
                MySqlHelperMy.CloseDbResource(con, null);
            }

            return existSameUrl;
        }
        /// <summary>
        /// 从SiteKindPageUrlTemp表中获取某个分类新增的页面url、标题等
        /// </summary>
        /// <param name="siteKindId"></param>
        /// <param name="detailTableName">保存详细内容的表名，即没有Temp的表名</param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public static DataTable GetKindUrlTemp(string siteKindId, string detailTableName, string fields)
        {
            fields = string.IsNullOrEmpty(fields) ? "url" : fields;//如果指定从数据库获取字段值，在字段名称前面加上逗号
            string command = "select " + fields
                + " from " + detailTableName + "Temp where isGetDetail=0 and siteKindId='" + siteKindId + "' ";            
            MySqlConnection con = MySqlHelperMy.GetConnection();          
            MySqlDataAdapter da = new MySqlDataAdapter(command, con);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }
        /// <summary>
        /// 直接从RssNews表读取新闻link
        /// </summary>
        /// <param name="siteId">RssSites中的SiteId</param>
        /// <param name="detailTableName"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public static DataTable GetRssNewsUrl(int siteId, string detailTableName, string fields)
        {
            string command = "select id,link,content from " + detailTableName + " where isGetContent=0 and siteId=" + siteId.ToString();
            MySqlConnection con = MySqlHelperMy.GetConnection();           
            MySqlDataAdapter da = new MySqlDataAdapter(command, con);
            DataSet ds = new DataSet();
            da.Fill(ds);

            return ds.Tables[0];
        }
        /// <summary>
        /// 保存最终内容到数据库
        /// </summary>
        /// <param name="siteKindId">站点分类ID</param>
        /// <param name="tableName">插入表名</param>
        /// <param name="content">内容</param>
        /// <param name="dicResult">其他属性</param>
        public static void SaveFinalContent(string siteKindId, string tableName, string content, StringDictionary dicResult, string startDetailUrl)
        {
            string command = "INSERT INTO " + tableName + " ( ";
            string nameField = "siteKindId";//, url
            string valueField = "@siteKindId";//, @url
            string key;
            MySqlConnection con = MySqlHelperMy.GetConnection();
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = con;
            cmd.Parameters.Add("@siteKindId", MySqlDbType.String, 20).Value = siteKindId;
            
            foreach (DictionaryEntry field in dicResult)
            {
                key = field.Key.ToString();
                nameField += "," + key;
                valueField += ",@" + key;

                cmd.Parameters.Add("@" + key, System.Data.DbType.String).Value = field.Value.ToString(); 
            }
            command = command + nameField + ") values (" + valueField + ")";//插入内容
            string updateCmd = "update " + tableName + "Temp set  isGetDetail=1 where url=@url ";//更新Temp,标记为已经获取内容//清空字段title='完', summary=null, img=null, author=null, actor=null,
            cmd.CommandText = command;

            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                //将SiteKindPageUrlTemp表对应的url记录标记为已经获取内容isGetDetail=1
                cmd.CommandText = updateCmd;
                cmd.Parameters.Clear();
                cmd.Parameters.Add("@url", MySqlDbType.String, 200).Value = startDetailUrl;
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error("保存最终内容失败. table=" + tableName, ex);
            }
            finally
            {
                con.Close();
            }
        }
        /// <summary>
        /// 保存内容
        /// </summary>
        /// <param name="id"></param>
        /// <param name="tableName"></param>
        /// <param name="content"></param>
        /// <param name="dicResult"></param>
        public static void SaveRssNewsContent(string id, string tableName, bool isGetContentSuccess, StringDictionary dicResult)
        {
            string command = null;
            if (isGetContentSuccess)//获取内容成功
            {
                command = "update " + tableName + " set isGetContent=1, haveContent=1, createTime=@createTime, content=@content where id=@id";
            }
            else//没有获取到内容
            {
                command = "update " + tableName + " set isGetContent=1, haveContent=0, createTime=@createTime where id=@id";
            }
            MySqlConnection con = MySqlHelperMy.GetConnection();
            MySqlCommand cmd = new MySqlCommand(command, con);
            cmd.Parameters.Add("@createTime", MySqlDbType.DateTime).Value = DateTime.Now;
            cmd.Parameters.Add("@id", MySqlDbType.String, 20).Value = id;

            string key;
            if (isGetContentSuccess)
            {
                foreach (DictionaryEntry field in dicResult)
                {
                    key = field.Key.ToString();
                    if (key == "content")
                    {
                        cmd.Parameters.Add("@content", MySqlDbType.Text).Value = field.Value.ToString();
                        break;
                    }
                }
            }
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();                
            }
            catch (Exception ex)
            {
                LogHelper.Log.Error("保存最终内容失败. table=" + tableName, ex);
            }
            finally
            {
                con.Close();
            }
        }
    }
}
